//
//  Resource.m
//  RepasoApp
//
//  Created by Vicente Vicens Camarena on 02/10/11.
//  Copyright 2011 Imathink World, S.L.N.E. All rights reserved.
//

#import "Resource.h"

@implementation Resource

@synthesize resourceId = resourceId_;
@synthesize resourceTitle = resourceTitle_;
@synthesize resourceDescription = resourceDescription_;
@synthesize resourceURL = resourceURL_;
@synthesize resourceURL2 = resourceURL2_;
@synthesize resourceType = resourceType_;
@synthesize data = data_;

//Designated initializer
- (id)initWithDictionary:(NSDictionary *)dictionary
{
    self = [super init];
    if (self) {
        // Initialization code here.
        self.resourceId = [dictionary objectForKey:@"resource_id"];
        self.resourceTitle = [dictionary objectForKey:@"resource_title"];
        self.resourceDescription = [dictionary objectForKey:@"resource_description"];
        self.resourceURL = [dictionary objectForKey:@"resource_url"];
        self.resourceURL2 = [dictionary objectForKey:@"resource_url_2"];
        self.resourceType = [dictionary objectForKey:@"resource_type"];
    }
    
    return self;
}

- (id)init
{
    return [self initWithDictionary:nil];
}

+ (Resource *)resourceWithDictionary:(NSDictionary *)dictionary {
    return [[[Resource alloc] initWithDictionary:dictionary] autorelease];
}

- (UIImage *)resourceImage {
    return [UIImage imageNamed:@"resource.png"];
}

+ (NSString*)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);
	
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}

- (NSString *) localPath{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.pdf", [Resource md5HexDigest: self.resourceURL2]]];
}

- (NSData *) data{
    if (data_ == nil){
        
        data_ = [[NSData dataWithContentsOfFile: [self localPath]] retain];
    }
    
    return data_;
        
}

- (BOOL)isCached{
    return [[NSFileManager defaultManager] fileExistsAtPath: [self localPath]];
}

- (void) setData:(NSData *)data{
    [data writeToFile:[self localPath] atomically:NO];
    [data_ release];
    data_ = data;
    [data retain];
}

- (void)dealloc {
    [resourceId_ release];
    [resourceTitle_ release];
    [resourceDescription_ release];
    [resourceURL_ release];
    [resourceURL2_ release];
    [resourceType_ release];
    [super dealloc];
}

@end
